package com.chatgpt.base.utils;

import com.alibaba.fastjson.JSON;
import org.bouncycastle.crypto.digests.SHA3Digest;

import java.nio.charset.StandardCharsets;
import java.util.Random;

/**
 * 字符串工具
 *
 * @author yangjian
 */
public class StringUtil {

  /**
   * 生成随机字符串
   *
   * @param length 字符串长度
   * @return 返回随机字符串
   */
  public static String genRandomStr(int length) {
    String base = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKMNLOPQRSTUVWXYZ";
    Random random = new Random();
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < length; i++) {
      int number = random.nextInt(base.length());
      sb.append(base.charAt(number));
    }
    return sb.toString();
  }

  /**
   * 生成一个随机数字字符串 Attention : The maximum length is 16
   *
   * @param length 字符串长度
   * @return 返回数字字符串
   */
  public static String genRandomNum(int length) {
    if (length > 16) {
      throw new IndexOutOfBoundsException("Can not generate more than 16 bit string");
    }
    return (((Double) Math.random()).toString()).substring(2, length + 2);
  }

  /* 将对象转为 JSON 字符串 */
  public static String jsonEncode(Object obj) {
    return JSON.toJSONString(obj);
  }

  /* JSON 字符串还原为对象 */
  public static <T> T jsonDecode(String json, Class<T> clazz) {
    return JSON.parseObject(json, clazz);
  }

  /**
   * 生成一个密码
   *
   * @param source         明文
   * @param salt           盐值
   * @return 返回加密后的密码
   */
  public static String genPassword(String source, String salt) {
    String data = source + salt;
    return sha3Sha256(data);
  }


  // sha3.SHA256 算法实现
  public static String sha3Sha256(String input) {
    SHA3Digest sha3Digest = new SHA3Digest(256);
    byte[] inputBytes = input.getBytes(StandardCharsets.UTF_8);
    sha3Digest.update(inputBytes, 0, inputBytes.length);
    // 计算哈希值
    byte[] hash = new byte[sha3Digest.getDigestSize()];
    sha3Digest.doFinal(hash, 0);

    // 输出 16 进制字符串
    StringBuilder hexStringBuilder = new StringBuilder(2 * hash.length);
    for (byte b : hash) {
      hexStringBuilder.append(String.format("%02x", b));
    }
    return hexStringBuilder.toString();
  }
}
